import { requestClient, baseRequestClient } from '#/api/request';
import { useAccessStore } from '@vben/stores';

export namespace TaskApi {
  /** 任务列表查询参数 */
  export interface TaskListParams {
    page?: number;
    per_page?: number;
    search?: string;
    status?: 'inactive' | 'active';
    service_type?: string;
    start_date?: string;
    end_date?: string;
    sort_by?: string;
    sort_order?: 'asc' | 'desc';
  }

  /** 任务记录接口 */
  export interface TaskRecord {
    id: string;
    tenant_id: string;
    name: string;
    service_type: string;
    status: 'inactive' | 'active';
    start_time: string;
    end_time: string;
    settlement_cycle: string; // 新增
    min_fee: string | number;
    max_fee: string | number;
    billing_unit?: string | null;
    gender_requirement: string; // 新增
    education_requirement: string; // 新增
    min_age: number; // 新增
    max_age: number; // 新增
    work_location: string;
    work_time: string; // 新增
    work_content: string; // 改为必需字段
    work_compensation: string; // 新增
    work_benefits: string; // 新增
    qr_code_url: string | null; // 新增
    created_at: string;
    updated_at: string; // 新增
    applications: any[]; // 新增，具体类型待定义
    applications_count?: number; // 保留作为可选字段
  }

  /** 分页响应结构 */
  export interface TaskListResponse {
    data: TaskRecord[];
    current_page: number;
    per_page: string | number; // 改为 string，因为后端返回的是字符串
    total: number;
    last_page: number;
    from: number;
    to: number;
    // 新增 Laravel 分页器的完整字段
    first_page_url: string;
    last_page_url: string;
    next_page_url: string | null;
    prev_page_url: string | null;
    path: string;
    links: Array<{
      url: string | null;
      label: string;
      active: boolean;
    }>;
  }
  /** API响应包装 */
  export interface ApiResponse<T> {
    success: boolean;
    data: T;
    message?: string;
  }

  export interface TaskApplicationListParams {
    page?: number;
    per_page?: number;
    search?: string;
    status?: string;
    applied_start?: string;
    applied_end?: string;
    sort_by?: string;
    sort_order?: 'asc' | 'desc';
  }

  export interface TaskApplicationRecord {
    id: string;
    task_id: string;
    tenant_id: string;
    freelancer_id: string | null;
    application_number: string;
    name: string;
    phone: string;
    email?: string | null;
    status: string;
    applied_at: string | null;
    processed_at?: string | null;
    created_at: string;
    updated_at: string;
    application_note?: string | null;
    rejection_reason?: string | null;
    freelancer?: {
      id: string;
      name: string;
      phone?: string | null;
    } | null;
    processor?: {
      id: string;
      name: string;
    } | null;
  }

  export interface PaginatedResponse<T> {
    data: T[];
    current_page: number;
    per_page: number | string;
    total: number;
    last_page: number;
    from: number | null;
    to: number | null;
    first_page_url: string;
    last_page_url: string;
    next_page_url: string | null;
    prev_page_url: string | null;
    path: string;
    links: Array<{
      url: string | null;
      label: string;
      active: boolean;
    }>;
  }

  export interface AdminTaskApplicationsResponse {
    task: TaskRecord;
    applications: PaginatedResponse<TaskApplicationRecord>;
  }
}

/**
 * 获取任务列表
 */
/**
 * 获取任务列表
 * @param params 查询参数
 * @returns 任务列表响应数据
 */
// export async function getTaskListApi(params: TaskApi.TaskListParams) {
//   try {
//     const response = await requestClient.get<TaskApi.ApiResponse<any>>('/tenant/tasks', {
//       params,
//     });
    
//     // 数据转换，确保类型匹配
//     if (response.success && response.data) {
//       const transformedData: TaskApi.TaskListResponse = {
//         data: response.data.data,
//         current_page: response.data.current_page,
//         per_page: parseInt(response.data.per_page), // 转换为数字
//         total: response.data.total,
//         last_page: response.data.last_page,
//         from: response.data.from,
//         to: response.data.to,
//       };
      
//       return {
//         ...response,
//         data: transformedData
//       };
//     }
    
//     return response;
//   } catch (error) {
//     console.error('API调用失败:', error);
//     throw error;
//   }
// }

export async function getTaskListApi(params: TaskApi.TaskListParams) {
  return requestClient.get<TaskApi.TaskListResponse>('/api/tenant/tasks', {
    params,
  });
}

export async function getTenantTaskListApi(
  tenantId: number | string,
  params: TaskApi.TaskListParams,
) {
  return requestClient.get<TaskApi.TaskListResponse>(`/api/admin/tenants/${tenantId}/tasks`, {
    params,
  });
}

export async function getTenantTaskApplicationsApi(
  tenantId: number | string,
  taskId: number | string,
  params: TaskApi.TaskApplicationListParams,
) {
  return requestClient.get<TaskApi.AdminTaskApplicationsResponse>(
    `/api/admin/tenants/${tenantId}/tasks/${taskId}/applications`,
    {
      params,
    },
  );
}

export async function manualCreateTenantTaskApplicationApi(
  tenantId: number | string,
  taskId: number | string,
  data: FormData,
) {
  return requestClient.post<TaskApi.AdminTaskApplicationsResponse>(
    `/api/admin/tenants/${tenantId}/tasks/${taskId}/applications/manual`,
    data,
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    },
  );
}

export async function previewTenantTaskApplicationContractApi(
  tenantId: number | string,
  taskId: number | string,
  applicationId: number | string,
) {
  const accessStore = useAccessStore();
  const token = accessStore.accessToken;

  const response = await baseRequestClient.get(
    `/api/admin/tenants/${tenantId}/tasks/${taskId}/applications/${applicationId}/contract`,
    {
      responseType: 'blob',
      headers: token ? { Authorization: `Bearer ${token}` } : undefined,
    },
  );
  return response.data as Blob;
}
/**
 * 获取任务详情
 */
export async function getTaskDetailApi(id: string) {
  return requestClient.get<TaskApi.ApiResponse<TaskApi.TaskRecord>>(`/api/tenant/tasks/${id}`);
}

/**
 * 创建任务
 */
export async function createTaskApi(data: Partial<TaskApi.TaskRecord>) {
  return requestClient.post<TaskApi.ApiResponse<TaskApi.TaskRecord>>('/api/tenant/tasks', data);
}

/**
 * 更新任务
 */
export async function updateTaskApi(id: string, data: Partial<TaskApi.TaskRecord>) {
  return requestClient.put<TaskApi.ApiResponse<TaskApi.TaskRecord>>(`/api/tenant/tasks/${id}`, data);
}

/**
 * 删除任务
 */
export async function deleteTaskApi(id: string) {
  return requestClient.delete<TaskApi.ApiResponse<null>>(`/api/tenant/tasks/${id}`);
}
